package com.pacvue.configuration;

import com.pacvue.properties.RedissonLockProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Redisson分布式锁自动配置类
 * 
 * @author pacvue
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "redisson-lock", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(RedissonLockProperties.class)
public class RedissonLockAutoConfiguration {

    @Bean
    public RedissonClient redissonClient(RedissonLockProperties properties) {
        Config config = new Config();
        
        // 配置单机模式
        config.useSingleServer()
            .setAddress("redis://" + properties.getRedis().getHost() + ":" + properties.getRedis().getPort())
            .setPassword(properties.getRedis().getPassword())
            .setDatabase(properties.getRedis().getDatabase())
            .setConnectionMinimumIdleSize(properties.getRedis().getConnectionMinimumIdleSize())
            .setConnectionPoolSize(properties.getRedis().getConnectionPoolSize())
            .setConnectTimeout(properties.getRedis().getConnectionTimeout() * 1000)
            .setTimeout(properties.getRedis().getCommandTimeout() * 1000)
            .setRetryAttempts(properties.getRedis().getRetryAttempts());

        RedissonClient redissonClient = Redisson.create(config);
        log.info("Redisson分布式锁客户端初始化成功 - host: {}, port: {}", 
            properties.getRedis().getHost(), properties.getRedis().getPort());
        
        return redissonClient;
    }
}
